package com.example.bigworkdemo.web.controller;

import com.example.bigworkdemo.bean.user;
import com.example.bigworkdemo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private userService userService;
    @GetMapping("/login")
    public String login(Model m)
    {
        m.addAttribute("user",new user());
         return "login";
    }
    @PostMapping("/loginValid")
    public String loginValid(@Valid user u, BindingResult br,Model m){
        if(br.hasErrors()){
            List<ObjectError> list = br.getAllErrors();
            for(ObjectError error:list){
                System.out.println("验证信息"+error.getDefaultMessage());
            }
            //跳转掉userInfo.jsp;
            return "login";
        }
        //符合。跳转
        try {
            user userInfo =  userService.login(u);
            //密码正确
            m.addAttribute("user",userInfo);
            return "index";
        } catch (Exception e) {
            //1.获取异常信息
            String msg = e.getMessage();
            //2.将异常信息添加到模型对象中
            m.addAttribute("msg",msg);
            return "error";
        }
    }
}
